import { Session, Local } from '@/utils/storage';
import { validatenull, validURL } from '@/utils/validate';
import { loginByUsername, getUserInfo, logout, refreshToken } from '@/api/login';
import { deepClone, encryption } from '@/utils/common';
import webiste from '@/utils/website';
import { formatRoutes } from '@/router/utils';
import router from '@/router/index';
import { getMenu, getTopMenu } from '@/api/menu';
import { defineStore } from 'pinia';

// const router = useRouter();
// 格式化菜单，加上默认图标等
function formatMenu(ele: any) {
	const menu = webiste.menu;
	const propsConfig = menu.props;
	const propsDefault = {
		label: propsConfig.label || 'name',
		path: propsConfig.path || 'path',
		icon: propsConfig.icon || 'icon',
		children: propsConfig.children || 'children',
	};
	const icon = ele[propsDefault.icon];
	ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
	const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
	if (!isChild) ele[propsDefault.children] = [];
}

interface UserStateType {
	userInfo: Record<string, any>;
	permissions: any;
	roles: string[];
	menu: Array<Record<string, any>>;
	slidebarMenu: Array<Record<string, any>>;
	buttonMenu?: Array<Record<string, any>>;
	// name: string;
	// avatar: string;
	access_token: string;
	refresh_token: string;
}

interface UserInfoType {
	username?: string;
	password?: string;
	code?: string;
	randomStr?: string;
	[prop: string]: any;
}

const useUserStore = defineStore('user', {
	state: (): UserStateType => ({
		userInfo: {},
		permissions: [],
		roles: [],
		menu: [], //所有菜单
		slidebarMenu: [], //侧边栏菜单
		access_token: '', //token
		refresh_token: '',
	}),

	actions: {
		// 根据用户名登录
		loginByUsername(userInfo: UserInfoType) {
			let user: UserInfoType = {};
			if (webiste.passwordEnc) {
				// 对密码加密
				user = encryption({
					data: userInfo,
					key: import.meta.env.VITE_APP_LOGIN_KEY,
					param: ['password'],
				});
			} else {
				user = userInfo;
			}
			return new Promise((resolve, reject) => {
				loginByUsername(user.username, user.password, user.code, user.randomStr)
					.then((res: Record<string, any>) => {
						console.log('loginByUsername', res);
						const data = res;
						this.set_access_token(data.access_token);
						this.set_refresh_token(data.refresh_token);
						// this.getUserInfo();
						// this.getMenu();
						resolve('resolve');
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 刷新token
		refreshToken() {
			return new Promise((resolve, reject) => {
				refreshToken()
					.then((res: Record<string, any>) => {
						const data = res;
						this.set_access_token(data.access_token);
						this.set_refresh_token(data.refresh_token);

						// commit('CLEAR_LOCK');
						resolve('success');
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 查询用户信息
		getUserInfo() {
			return new Promise((resolve, reject) => {
				getUserInfo()
					.then((res) => {
						const data = res.data || {};
						this.set_user_info(data.sysUser);
						this.set_roles(data.roles || []);
						this.set_permissions(data.permissions || []);
						resolve(data);
					})
					.catch(() => {
						reject();
					});
			});
		},
		// 登出
		handleLogOut() {
			console.log('--Logout');
			return new Promise((resolve, reject) => {
				logout()
					.then(() => {
						this.fedLogOut();
						// router.replace('/login');
						location.href = '/#/login';
						location.reload();
						resolve('succsss');
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 注销session
		fedLogOut() {
			return new Promise((resolve) => {
				this.menu = [];
				this.permissions = [];
				this.userInfo = {};
				this.access_token = '';
				this.refresh_token = '';
				Session.remove('menu');
				Session.remove('permissions');
				Session.remove('userinfo');
				Local.remove('access_token');
				Local.remove('refresh_token');
				resolve('succsss');
			});
		},
		// 获取系统菜单
		getMenu() {
			// 记录用户点击顶部信息，保证刷新的时候不丢失
			// commit('LIKE_TOP_MENUID', obj);

			return new Promise((resolve) => {
				getMenu().then((res) => {
					const data = res.data;

					const menu = deepClone(data);
					menu.forEach((ele: any) => {
						formatMenu(ele);
					});
					// 将菜单存起来
					this.set_menu(menu);
					// 根据菜单生成路由
					this.set_routes_form_menu(menu);
					//菜单分类
					this.set_menu_category(menu);

					resolve(menu);
				});
			});
		},
		//顶部菜单
		getTopMenu() {
			return new Promise((resolve) => {
				getTopMenu().then((res) => {
					const data = res.data.data || [];
					resolve(data);
				});
			});
		},
		set_access_token(access_token: string) {
			this.access_token = access_token;
			Local.set('access_token', access_token);
		},
		set_refresh_token(rfToken: string) {
			this.refresh_token = rfToken;
			Local.set('refresh_token', rfToken);
		},
		set_user_info(userInfo: any) {
			this.userInfo = userInfo;
			Session.set('userInfo', userInfo);
			console.log('set_userinfoo', userInfo);
		},
		set_menu(menu: any) {
			this.menu = menu;
			Session.set('menu', menu);
		},

		set_roles(roles: string[]) {
			this.roles = roles;
		},
		set_permissions(permissions: any) {
			const list: Record<string, any> = {};
			for (let i = 0; i < permissions.length; i++) {
				list[permissions[i]] = true;
			}

			this.permissions = list;
			Session.set('permissions', list);
		},
		// 从缓存设置store，刷新时候调用
		set_store_form_storage() {
			// console.log('set_store_form_storage--------------------------');
			this.menu = Session.get('menu') || [];
			// this.set_menu(Session.get('menu') || []);
			this.set_routes_form_menu(this.menu);
			this.set_menu_category(this.menu);
			this.permissions = Session.get('permissions') || [];
			this.userInfo = Session.get('userInfo') || {};
			this.access_token = Local.get('access_token');
			this.refresh_token = Local.get('refresh_token');
		},
		// 根据菜单设置路由
		set_routes_form_menu(menu: any) {
			const routes = formatRoutes(menu, true);
			routes.forEach((route) => router.addRoute(route));
		},
		// 将菜单分类成侧边栏菜单、按钮菜单等
		set_menu_category(menu: any) {
			this.slidebarMenu = ergodicArr(menu);
			// console.log('his.slidebarMenu', this.menu);
			function ergodicArr(arr: any, result: any[] = []) {
				let count = 0;
				arr.forEach((item: anyObj, index: number) => {
					if (item.children && item.children.length) {
						result[count] = {
							...item,
						};
						result[count].children = [];
						ergodicArr(item.children, result[count].children);
						count++;
					} else {
						// 左菜单和外部菜单放进 slidebarMenu
						if (item.menuType === '0' || item.menuType === '4') {
							result.push(item);
							count++;
						}
					}
				});
				return result;
			}
		},
	},
});

export default useUserStore;
